package org.micode.common.utils;

import java.util.Random;

public class RandomUtils {

    /**
     * * 生成随机数
     * * @param num 位数
     * * @return
     */
    public static String createRandomNum(int num) {
        StringBuilder randomNumStr = new StringBuilder();
        for (int i = 0; i < num; i++) {
            int randomNum = (int) (Math.random() * 10);
            randomNumStr.append(randomNum);
        }
        return randomNumStr.toString();
    }

    /**
     * 生成随机用户名，数字和字母组成
     */
    public static String getStringRandom(int length) {
        StringBuilder val = new StringBuilder();
        Random random = new Random();
        //参数length，表示生成几位随机数
        for (int i = 0; i < length; i++) {
            String charOrNum = random.nextInt(2) % 2 == 0 ? "char" : "num";
            //输出字母还是数字
            if ("char".equalsIgnoreCase(charOrNum)) {
                //输出是大写字母还是小写字母
                int temp = random.nextInt(2) % 2 == 0 ? 65 : 97;
                val.append((char) (random.nextInt(26) + temp));
            } else {
                val.append(String.valueOf(random.nextInt(10)));
            }
        }
        return val.toString();
    }

    public static String addZeroInWhile(int num, int len) {
        StringBuilder sf = new StringBuilder();
        sf.append(num);
        int diff = len - sf.length();
        if (diff > 0) {
            while (sf.length() < len) {//若长度不足进行补零
                sf.insert(0, "0");//每次都在最签名补零
            }
        }
        return sf.toString();
    }
}
